import Cookies from 'js-cookie'
import { forEach, hasOneOf } from './tools'

const TokenKey = 'token'
export const USER_NAME = 'username'
export const MENU_LIST = 'menus'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export const removeCookieKey = name => {
  Cookies.remove(name)
}

export const setUserName = name => {
  Cookies.set(USER_NAME, name, { expires: 1 })
}

export const getUserName = () => {
  const name = Cookies.get(USER_NAME)
  if (name) return name
  else return false
}

export const setRoutes = routes => {
  Cookies.set(MENU_LIST, JSON.stringify(routes), {
    expires: 1
  })
}

export const getRoutes = () => {
  if (Cookies.get(MENU_LIST)) {
    const routes = JSON.parse(Cookies.get(MENU_LIST))
    if (routes) return routes
    else return []
  } else {
    return []
  }
}

export const hasChild = item => {
  return item.children && item.children.length !== 0
}

const showThisMenuEle = (item, access) => {
  if (item.meta && item.meta.access && item.meta.access.length) {
    if (hasOneOf(item.meta.access, access)) return true
    else return false
  } else return true
}

/**
 * @param {Array} list 通过路由列表得到菜单列表
 * @returns {Array}
 */
export const getMenuByRouter = (list, access) => {
  const res = []
  const menus = getRoutes()
  forEach(list, item => {
    if (
      (!item.meta || (item.meta && !item.meta.hideInMenu)) &&
      menus.includes(item.name)
    ) {
      const obj = {
        icon: (item.meta && item.meta.icon) || '',
        name: item.name,
        meta: item.meta,
        path: item.path
      }
      if (
        (hasChild(item) || (item.meta && item.meta.showAlways)) &&
        showThisMenuEle(item, access)
      ) {
        obj.children = getMenuByRouter(item.children, access)
      }
      if (item.meta && item.meta.href) obj.href = item.meta.href
      if (showThisMenuEle(item, access)) res.push(obj)
    }
  })
  return res
}

export const getMenuList = (data) => {
  const menus = []
  const original = ['login', 'error_404']
  forEach(data, item => {
    menus.push(item.uri)
    if (item.children) {
      forEach(item.children, child => {
        menus.push(child.uri)
      })
    }
  })
  return menus.concat(original)
}

/**
 * @description 本地存储和获取标签导航列表
 */
export const setTagNavListInLocalstorage = list => {
  localStorage.tagNaveList = JSON.stringify(list)
}

/**
 * @returns {Array} 其中的每个元素只包含路由原信息中的name, path, meta三项
 */
export const getTagNavListFromLocalstorage = () => {
  const list = localStorage.tagNaveList
  return list ? JSON.parse(list) : []
}

